package org.example.Utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.example.Pojo.Permission;
import org.example.Service.Impl.PermissionServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Aspect
@Component
public class RequirePermissionAspect {
    @Autowired
    private PermissionServiceImpl permissionServiceImpl;
    @Pointcut("@annotation(requirePermission)")
    public void requirePermissionPointCut(RequirePermission requirePermission) {}

    @Around("requirePermissionPointCut(requirePermission)")
    public Object around(ProceedingJoinPoint joinPoint, RequirePermission requirePermission) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String headerValue = request.getHeader("uid");
        List<Permission> permission_list = permissionServiceImpl.GetUserPermissions(headerValue);
        String permission_str = requirePermission.value();
        int forward = requirePermission.forward();
        if (forward == 1) {
            //正向授权
            for (Permission permission : permission_list) {
                if (permission.getAuthority().equals(permission_str)){
                    return joinPoint.proceed();
                }
            }
            return UnionResult.Failure("permission deny");
        }else {
            //反向授权
            for (Permission permission : permission_list) {
                if (permission.getAuthority().equals(permission_str)) {
                    return UnionResult.Failure("permission deny");
                }
            }
            return joinPoint.proceed();
        }
    }
}
